package com.ccgk.logistics.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ccgk.common.MyCollectionUtils;
import com.ccgk.common.page.PaginationVo;
import com.ccgk.common.web.RequestUtils;
import com.ccgk.logistics.domain.Menu;
import com.ccgk.logistics.domain.MenuType;
import com.ccgk.logistics.domain.Role;
import com.ccgk.logistics.domain.User;
import com.ccgk.logistics.service.MenuService;
import com.ccgk.logistics.service.RoleService;
import com.ccgk.logistics.service.UserService;
import com.ccgk.logistics.vo.MenuTypeVO;
import com.ccgk.logistics.vo.MenuVO;
import com.ccgk.logistics.vo.RoleVO;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;
	
	/**登录页*/
	@RequestMapping("/login")
	public String showLogin(){
		return "login";
	}
	
	/**登录页*/
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request){
		Enumeration<String> attrNames = request.getSession().getAttributeNames();
		while(attrNames.hasMoreElements()){
			request.getSession().removeAttribute(attrNames.nextElement());
		}
		return "redirect:/";
	}
	
	/**登录*/
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(User user,HttpServletRequest reuqest){
		if(userService.validUser(user)){
			user = userService.getUserByLoginName(user.getName());
			List<Menu> configedMenus = userService.getMenusByUserId(user.getId());
			
			List<MenuType> menuTypes = menuService.getMenuTypes();
			List<MenuTypeVO> menuTypeVOs = new ArrayList<MenuTypeVO>();
			for(MenuType menuType : menuTypes){
				
				MenuTypeVO menuTypeVO = new MenuTypeVO();
				menuTypeVO.setDisplayable(false);
				BeanUtils.copyProperties(menuType, menuTypeVO);
				menuTypeVOs.add(menuTypeVO);
				
				List<Menu> menus = menuService.getMenusOfType(menuType.getId());
				List<MenuVO> menuVOs = new ArrayList<MenuVO>();
				menuTypeVO.setMenuvos(menuVOs);
				for(Menu menu : menus){
					MenuVO menuVO = new MenuVO();
					BeanUtils.copyProperties(menu, menuVO);
					menuVOs.add(menuVO);
					
					for(Menu m : configedMenus){
						if(m.getId().equals(menu.getId())){
							menuVO.setChecked(true);
							menuTypeVO.setDisplayable(true);
							break;
						}
					}
				}
			}
			reuqest.getSession().setAttribute("menuTypes",menuTypeVOs);
			reuqest.getSession().setAttribute("loginUser",user);
			return "redirect:/order/list";
		}else{
			reuqest.setAttribute("errorMsg", "用户名，密码输入有误，或者您的账号已冻结，请联系管理员！");
			return "login";
		}
	}
	
	/**加载单个用户*/
	@RequestMapping("/{id}")
	public String loadUserById(@PathVariable("id")Integer id,Model model){
		User user = userService.getUserById(id);
		
		//处理用户当前所属角色
		List<Role> checkedRoles = userService.getRolesByUserId(id);
		List<Role> roles = roleService.getAllRoles();
		List<RoleVO> roleVos = new ArrayList<RoleVO>();
		for(Role role : roles){
			RoleVO rv = new RoleVO();
			BeanUtils.copyProperties(role, rv);
			for(Role crv : checkedRoles){
				if(rv.getId().equals(crv.getId())){
					rv.setChecked(true);
					break;
				}
			}
			roleVos.add(rv);
		}
		
		
		model.addAttribute("roleVos", roleVos);
		
		model.addAttribute("user", user);
		return "user/edit";
	}
	
	/**更新用户*/
	@ResponseBody
	@RequestMapping(value="/{id}",method=RequestMethod.POST)
	public String update(User user){
		User _user = userService.getUserByLoginName(user.getName());
		if(_user != null && !_user.getId().equals(user.getId()))
			return "{flag:1}";
		userService.update(user);
		return "{flag:0}";
	}
	
	/**查询用户列表*/
	@RequestMapping("/list")
	public String list(HttpServletRequest request){
		int currentPage = RequestUtils.getInt(request,"currentPage",1);
		int pageSize = RequestUtils.getInt(request,"pageSize",PaginationVo.DEFAULT_PAGESIZE);
		String name = request.getParameter("name");
		int activable = RequestUtils.getInt(request,"activable",0);
		UserService.UserCriteria criteria = new UserService.UserCriteria();
		if(StringUtils.isNotBlank(name))
			criteria.nameLike(name);
		if(activable == 1){
			criteria.activable(true);
		}else if(activable == 2){
			criteria.activable(false);
		}
		PaginationVo<User> result = userService.searchUsers(criteria, currentPage, pageSize);
		request.setAttribute("result",result);
		return "user/list";
	}
	
	/**删除用户*/
	@ResponseBody
	@RequestMapping("/delete")
	public String delete(@RequestParam("id")String ids,Model model){
		Integer[] idIntArray = MyCollectionUtils.splitToIntArray(ids);
		userService.batchDelete(idIntArray);
		return "{success:true}";
	}
	
	/**激活用户*/
	@ResponseBody
	@RequestMapping("/active")
	public String active(@RequestParam("id")String ids,Model model){
		Integer[] idIntArray = MyCollectionUtils.splitToIntArray(ids);
		userService.batchActive(idIntArray);
		return "{success:true}";
	}
	
	/**删除用户*/
	@ResponseBody
	@RequestMapping("/disable")
	public String disable(@RequestParam("id")String ids,Model model){
		Integer[] idIntArray = MyCollectionUtils.splitToIntArray(ids);
		userService.batchDisable(idIntArray);
		return "{success:true}";
	}
	
	/**新增用户页*/
	@RequestMapping("/add")
	public String showAdd(){
		return "user/add";
	}
	
	/**新增用户*/
	@ResponseBody
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(User user,HttpServletResponse response){
		if(userService.getUserByLoginName(user.getName()) != null){
			return "{flag:1}";
		}
		userService.addNewUser(user);
		return "{flag:0,id:" + user.getId() + "}";
	}

}
